package com.generator.code.util;

import com.alibaba.fastjson.JSON;
import com.generator.code.model.GenTableEntity;
import com.google.common.collect.Maps;
import org.springframework.beans.BeanUtils;
import org.springframework.cglib.beans.BeanMap;

import java.util.Map;

/**
 * @author guoq.z
 * @date 2021/4/2
 */
public class BeanUtil {

    public static Map<String, Object> beanConvertMap(Object source) {
        BeanMap beanMap = BeanMap.create(source);

        Map<String, Object> map = Maps.newHashMap();
        for (Object keyObj : beanMap.keySet()) {
            String key = ((String) keyObj);
            Object value = beanMap.get(key);
            map.put(key, value);
        }

        return map;
    }

    public static <T> T mapConvertBean(Map<String, Object> map, Class<T> clazz) {
        String jsonString = JSON.toJSONString(map);
        return JSON.parseObject(jsonString, clazz);
    }

    public static <T> T convertBean(Object source, Class<T> clazz) {
        try {
            T t = clazz.newInstance();
            BeanUtils.copyProperties(source, t);
            return t;
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return null;
    }

    public static void main(String[] args) {
        GenTableEntity genTableEntity = new GenTableEntity();
        genTableEntity.setTableName("aaaaa");

        Map<String, Object> stringObjectMap = beanConvertMap(genTableEntity);
        System.out.println(stringObjectMap);

        GenTableEntity genTableEntity1 = mapConvertBean(stringObjectMap, GenTableEntity.class);
        System.out.println(genTableEntity1);

    }
}
